#!/usr/bin/env python
# -*- coding: UTF-8 -*-
from io import BytesIO
from typing import List
from fastapi import APIRouter, File, HTTPException, Query, UploadFile
import pandas as pd

from app.types.apiproto.user_proto import YmUserCreate
from app.dao.user_dao import UserOperateDao, UserQueryDao
from app.service.usersvc.user_list_svc import UserListService
from app.types import apiproto

router = APIRouter(prefix="/user", tags=["用户相关接口"])


@router.post("/login")
async def login(param: apiproto.LoginRequest):
    """
    用户列表-演示
    """
    print(param)
    if param.username == "admin" and param.password == "ad123456":
        return {
            "success": True,
            "id": 1,
            "role": "admin",
            "username": param.username,
            "msg": "登录成功",
        }
    # 2022301042003 30391X
    elif UserQueryDao.login(param.username, param.password) != None:
        return {
            "success": True,
            "id": 2,
            "role": "student",
            "username": param.username,
            "msg": "登录成功",
        }
    else:
        return {"success": False, "msg": "用户名或密码错误"}


@router.post("/excel")
async def upload_excel(file: UploadFile = File(...)):
    if file is None:
        raise HTTPException(status_code=400, detail="请上传 Excel 文件")

    try:
        contents = await file.read()
        df = pd.read_excel(BytesIO(contents), engine="openpyxl")
        df = df.where(pd.notnull(df), None)
        UserOperateDao.delete_all()
        user_number = UserListService.save_users(df)

    except Exception as e:
        raise HTTPException(status_code=400, detail=f"Excel 读取失败: {str(e)}")

    return {"status": "success", "message": f"成功导入 {user_number} 条记录"}


@router.get("/major-stat")
def get_major_statistics():
    return UserOperateDao.count_students_by_major()


@router.get("/by-major")
def get_student_statistics_by_major(
    major: str = Query(..., description="专业名称"),
    response_model=List[YmUserCreate],
):
    """
    根据专业名称查询该专业下学生统计列表
    """
    return UserListService.get_statistics_by_major(major)
